import React, { Component } from 'react';
import { View, Text, FlatList, NativeModules, TouchableHighlight, Image, ScrollView, Modal, SafeAreaView, TouchableOpacity } from 'react-native';




import { Container, Header, Body, Button, List, ListItem } from 'native-base'
import Swiper from 'react-native-swiper'
import Icon from '../../../src/iconfont/Icon'
import LinearGradient from 'react-native-linear-gradient';
import WebView from 'react-native-autoheight-webview'
import Video from 'react-native-video'


import BaseHeader from '../../../Views/BaseHeader'
import net from '../../../net';

let vm = NativeModules.SYHomeVCViewModel
let goods_info_path = '/v1/goods/detail'

var header = {
    systemType: "ios",
}

var opt = {
    header,
    "Accept": "application/json",
    "Content-Type": "application/json"
}

function SkuBaseInfoView(props) {
    let info = props.info;
    let skuData = info.skuData;
    let sku = { properties_name: '' }
    if (skuData != undefined) {
        sku = skuData[0]
    }

    return (
        <View style={{ padding: 12, flexDirection: 'row' }}>
            <Image style={{ width: 92, height: 92, backgroundColor: 'black' }} source={{ uri: info.thumb }} />
            <View style={{ marginLeft: 10, flex: 1, flexDirection: 'row' }}>
                <View style={{ flex: 1, justifyContent: 'space-around' }}>
                    <Text style={{ color: '#ff0000' }}>{`￥${Math.floor(info.user_price)}.00`}</Text>
                    <Text style={{ fontSize: 12, color: '#333333' }}>{`已选择:${sku.properties_name}`}</Text>
                    <Text style={{ fontSize: 12, color: '#333333' }}>{`库存:${info.stock}`}</Text>
                </View>
                <Button style={{ width: 35, height: 35 }} transparent onPress={props.dismiss}>
                    <Icon name='tupianguanbix' size={30} color='#666666' />
                </Button>
            </View>
        </View>
    )
}

function SkuPropertySelectView(props) {
    let info = props.info;
    let skuData = info.skuData;
    if (skuData == undefined) {
        return null
    }
    return (
        <View style={{ padding: 12, width: '100%' }}>
            <Text style={{ fontSize: 12, color: '#666666' }}>产品选择</Text>
            <View style={{ padding: 5, flexWrap: 'wrap', flexDirection: 'row' }}>
                {
                    skuData.map((obj, idx) => {
                        return (
                            <Button style={{ backgroundColor: idx != 0 ? '#ffffff' : '#ff0000', borderColor: '#ff0000', minWidth: 35, maxHeight: 26, borderRadius: 13, overflow: 'hidden', paddingLeft: 10, paddingRight: 10, marginRight: 5, marginTop: 5, borderWidth: 1, justifyContent: 'center', alignItems: 'center' }}>
                                <Text style={{ color: idx == 0 ? '#ffffff' : '#ff0000', fontSize: 12 }}>{obj.properties_name}</Text>
                            </Button>
                        )
                    })
                }
            </View>
        </View>
    )
}

function SkuNumSelectView(props) {
    return (
        <View style={{ padding: 12, width: '100%' }}>
            <Text style={{ fontSize: 12, color: '#666666' }}>数量</Text>
            <Text style={{ fontSize: 12, color: '#333333' }}>1</Text>
        </View>
    )
}

function SkuView(props) {
    let data = props.data
    return (
        <Modal animationType='slide' visible={props.show} transparent={true}>
            <View style={{ flex: 1 }}>
                <SafeAreaView style={{
                    position: 'absolute',
                    bottom: 0,
                    left: 0,
                    right: 0,
                    height: 300,
                    backgroundColor: '#ffffff',
                }}>
                    <ScrollView style={{ flex: 1, paddingTop: 12, paddingBottom: 20 }}>
                        <SkuBaseInfoView info={data} dismiss={props.dismiss} />
                        <SkuPropertySelectView info={data} />
                        <SkuNumSelectView />
                    </ScrollView>

                    <View style={{ height: 44, flexDirection: 'row', backgroundColor: '#ff0000' }}>
                        <Button style={{ flex: 1, justifyContent: 'center' }} transparent onPress={props.checkOrder}>
                            <Text style={{ color: '#ffffff' }}>立即购买</Text>
                        </Button>
                    </View>
                </SafeAreaView>
            </View>
        </Modal>
    )
}

function VideoView(props) {
    return (
        <TouchableOpacity style={{ flex: 1, height: 375, justifyContent: 'center', alignItems: 'center', width: '100%', }}>
            <Video resizeMode='cover' style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, backgroundColor: '#000000' }}
                source={{ uri: props.video }} />
            <Button transparent>
                <Icon name='bofang2' backgroundColor='#00000080' size={35} color='#ffffff' />
            </Button>
        </TouchableOpacity>
    )
}

function ParamsSectionView(props) {
    return (
        <View style={{ backgroundColor: '#ffffff' }}>
            <List style={{ flex: 1 }}>
                <ListItem style={{ flexDirection: 'row', height: 45 }}>
                    <Text style={{ width: 50, fontSize: 14, fontWeight: 'bold', color: '#333333' }}>标题</Text>
                    <Text style={{ flex: 1, color: '#666666', fontSize: 12 }}>内容</Text>
                    <Image style={{ width: 50, height: 30, backgroundColor: 'black' }} />
                </ListItem>

                <ListItem style={{ flexDirection: 'row', height: 45 }}>
                    <Text style={{ width: 50, fontSize: 14, fontWeight: 'bold', color: '#333333' }}>标题</Text>
                    <Text style={{ flex: 1, color: '#666666', fontSize: 12 }}>内容</Text>
                    <Image style={{ width: 50, height: 30, backgroundColor: 'black' }} />
                </ListItem>

                <ListItem style={{ flexDirection: 'row', height: 45 }}>
                    <Text style={{ width: 50, fontSize: 14, fontWeight: 'bold', color: '#333333' }}>标题</Text>
                    <Text style={{ flex: 1, color: '#666666', fontSize: 12 }}>内容</Text>
                    <Image style={{ width: 50, height: 30, backgroundColor: 'black' }} />
                </ListItem>
            </List>
        </View>
    )
}

function WebViewTitle(props) {
    return (
        <View style={{ backgroundColor: '#ffffff', padding: 12, }}>
            <Text style={{ fontSize: 14, fontWeight: 'bold', color: '#333333' }}>商品详情</Text>
        </View>
    )
}

function BottomBarSmallButton(data) {
    let obj = data.obj;
    return (
        <TouchableHighlight underlayColor={'rgba(0,0,0,0)'}>
            <View style={{ width: 45, height: 49, backgroundColor: 'white', justifyContent: 'center', alignItems: 'center' }}>
                <Icon name={obj.icon} style={{ marginBottom: 10 }} size={20} />
                <Text style={{ fontSize: 10, color: '#333333' }}>{obj.name}</Text>
            </View>
        </TouchableHighlight>
    )
}

function BottomBarAddShopCarButton(data) {
    let name = data.name;
    return (
        <TouchableHighlight underlayColor={'rgba(0,0,0,0)'} style={{ flex: 1 }}>
            <View style={{ flex: 1, paddingLeft: 12, paddingRight: 12, height: 49, borderRadius: 10, overflow: 'hidden', backgroundColor: '#FF953B', justifyContent: 'center', alignItems: 'center' }}>
                <Text style={{ color: '#ffffff' }}>{name}</Text>
            </View>
        </TouchableHighlight>
    )
}

function BottomBarBuyNowButton(props) {
    return (
        <TouchableHighlight onPress={props.action} underlayColor={'rgba(0,0,0,0)'} style={{ flex: 1 }}>
            <View style={{ flex: 1, paddingLeft: 12, paddingRight: 12, borderRadius: 10, overflow: 'hidden', backgroundColor: '#F92924', justifyContent: 'center', alignItems: 'center' }}>
                <Text style={{ color: '#ffffff' }}>{props.name}</Text>
            </View>
        </TouchableHighlight>
    )
}

function PriceAndTimeView(data) {
    let info = data.info
    return (
        <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} colors={['#F92924', '#FD793D']} style={{ height: 60, borderTopLeftRadius: 10, flexDirection: 'row', borderTopRightRadius: 10 }}>
            <View style={{ flex: 1, paddingLeft: 12 }} >
                {/* 价格 */}
                <View style={{ flexDirection: 'row', alignItems: 'baseline' }}>
                    <Text style={{ color: '#ffffff', fontWeight: 'bold', fontSize: 16 }}>￥</Text>
                    <Text style={{ color: '#ffffff', fontWeight: 'bold', fontSize: 30 }}>{`${Math.floor(info.user_price)}`}</Text>
                    <Text style={{ color: '#ffffff', fontWeight: 'bold', fontSize: 20 }}>.00</Text>
                </View>
                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                    <Text style={{ color: '#ffffff', fontSize: 13 }}>{'原价'}</Text>
                    <Text style={{ textDecorationLine: 'line-through', color: '#ffffff', fontWeight: 'bold', fontSize: 13 }}>{`￥${Math.floor(info.shop_price)}.00`}</Text>
                </View>
            </View>

            <View style={{ flex: 1, paddingRight: 12, justifyContent: 'center', alignItems: 'flex-end' }} >
                <Text style={{ color: '#ffffff', textAlign: 'right', fontSize: 16 }}>限时抢购</Text>
                <View style={{ overflow: 'hidden', flexDirection: 'row', marginTop: 10 }}>
                    <View style={{ borderTopLeftRadius: 10, justifyContent: 'center', borderBottomLeftRadius: 10, overflow: 'hidden', backgroundColor: '#ffffff', borderColor: '#ffffff', borderWidth: 1 }}>
                        <Text style={{ marginLeft: 10, marginRight: 5, color: '#F92A24', fontSize: 12 }}>距结束</Text>
                    </View>
                    <View style={{ borderTopRightRadius: 10, justifyContent: 'center', borderBottomRightRadius: 10, overflow: 'hidden', borderColor: '#ffffff', borderWidth: 1 }}>
                        <Text style={{ marginLeft: 5, marginRight: 10, color: '#ffffff', fontSize: 12 }}>2天23:16:35</Text>
                    </View>
                </View>
            </View>
        </LinearGradient>
    )
}

function SectionViewLine() {
    return (
        <View style={{ height: 12, backgroundColor: '#f9f6f9' }} />
    )
}

function TitleAndDesView(data) {
    let info = data.info
    return (
        <View style={{ padding: 12, backgroundColor: '#ffffff' }}>
            <Text style={{ fontSize: 15, fontWeight: 'bold', color: '#333333' }}>菲拉格慕蓝色经典淡香水50ml男士香水淡香持久然清新优雅留香男</Text>
            <Text style={{ marginTop: 5, fontSize: 13, color: '#999999' }}>氨基酸清洁保湿泡沫清洁保湿洗面奶</Text>
        </View>
    )
}

export default class index extends Component {
    constructor(props) {
        super(props);
        this.state = {
            goodsInfo: {},
            showSku: false,
            webViewHeight: 0,
            goodsId: ''
        };
    }

    UNSAFE_componentWillMount() {
        this.props.navigation.setOptions({ headerTransparent: true, title: "" })
        this.fetchGoodsDetail()
    }

    async fetchGoodsDetail() {
        let { params } = this.props.route
        let goodsId = params.goodsId
        let res = await net.get(goods_info_path, { id: goodsId })
        let data = res.data
        this.setState({ goodsInfo: data, goodsId: goodsId })
    }

    componentDidMount() {
        this.props.navigation.setOptions({})
    }

    onScroll = (e) => {
        let contentOffset = e.nativeEvent.contentOffset;
        let y = contentOffset.y

        let op = y / 40.0;
        if (op < 0) {
            op = 0
        }
        this.props.navigation.setOptions({ headerTransparent: true, title: op, headerStyle: { opacity: 1 - op, backgroundColor: 'green' } });
    }

    cellClick = () => {
        this.props.navigation.goBack()
    }

    checkOrder = (ids) => {
        this.setState({ showSku: false }, () => {
            vm.checkOrder(ids, '1')
        })
    }

    buyNowBtnClick = () => {
        let { showSku } = this.state
        showSku = !showSku
        this.setState({ showSku })
        // this.props.navigation.navigate('Login')
    }

    renderBanner = (video, imgs) => {
        let arr = []
        arr.push(<VideoView video={video} />)
        for (const obj of imgs) {
            arr.push(<Image source={{ uri: obj }} style={{ height: 375, width: '100%', backgroundColor: '#00ff00' }} />)
        }
        return arr
    }

    onWebViewMessage = (event) => {
        this.setState({ webViewHeight: Number(event.nativeEvent.data) })
    }

    render() {
        let { goodsInfo, showSku, goodsId } = this.state
        let info = goodsInfo.data || {};
        let imgs = info.imgs || []
        let video = info.video || ''
        let dstr = info.description || ''
        let cstr = info.content
        let html = `<!DOCTYPE html>
        <html>
        
        <head>
            <meta charset="utf-8">
            <meta name="viewport"
                content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
            <link rel="apple-touch-icon-precomposed" href="./icon.png" />
            <meta name="apple-mobile-web-app-capable" content="yes" />
            <meta name="apple-mobile-web-app-title" content="测试" />
            <meta name="apple-mobile-web-app-status-bar-style" content="black" />
            <title>shanghai</title>
            <style>
                * {
                    margin: 0;
                    padding: 0;
                    font-family: PingFangSC-Regular, Verdana, Arial, '微软雅黑', '宋体';
                }
        
                html,
                body {
                    height: 100%;
                    overflow: hidden;
                    padding-bottom: env(safe-area-inset-bottom);
                    padding-bottom: constant(safe-area-inset-bottom);
                }
                img {
                    width:100%;
                }
                .page {
                    height: 100%;
                    padding:12px;
                    padding-top: 0;
                }
            </style>
        </head>
        
        <body>
            <div class="page">
            ${dstr}
            ${cstr}
            </div>
        </body>
        
        </html>`

        return (
            <Container style={{ flex: 1, backgroundColor: "#F8F8F8", display: 'flex', flexDirection: "column" }}>
                <Header span style={{ backgroundColor: 'red' }}>
                    <Body>
                        <BaseHeader title={'商品详情'} />
                    </Body>
                </Header>
                <ScrollView style={{ flex: 1, backgroundColor: '#ffffff' }}>
                    <View style={{ height: 375, paddingBottom: -50 }}>
                        <Swiper loop={false} showsPagination={false}>
                            {this.renderBanner(video, imgs)}
                        </Swiper>
                    </View>
                    <PriceAndTimeView info={info} />
                    <TitleAndDesView info={{}} />
                    <SectionViewLine />
                    <WebViewTitle />
                    <WebView source={{ html: html }} scrollEnabled={false}
                        onMessage={this.onWebViewMessage}
                        injectedJavaScript='window.ReactNativeWebView.postMessage(document.body.scrollHeight)'
                    />
                </ScrollView>
                {/* bottom */}
                <View style={{ paddingLeft: 10, paddingRight: 10, backgroundColor: 'white', display: 'flex', width: '100%', flexDirection: 'row', alignItems: 'center' }}>
                    <View style={{ paddingLeft: 10, flexDirection: 'row', paddingRight: 10, justifyContent: 'space-around' }}>
                        <BottomBarSmallButton obj={{ icon: 'kefu', name: '客服' }} />
                        <BottomBarSmallButton obj={{ icon: 'shoucang', name: '收藏' }} />
                    </View>
                    <View style={{ flex: 1, height: 36, flexDirection: 'row', alignItems: 'center' }}>
                        <View style={{ width: 5 }} />
                        <BottomBarBuyNowButton name='立即购买' action={this.buyNowBtnClick} />
                    </View>
                </View>
                <SkuView show={showSku} data={info} checkOrder={this.checkOrder.bind(this, goodsId)} dismiss={() => { this.setState({ showSku: false }) }} />
            </Container>
        );
    }
}
